package com.itheima.d03_net_chat;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Objects;

public class ChatRunnable implements Runnable {
    private Socket socket;

    public ChatRunnable(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try (java.io.InputStream is = socket.getInputStream();
             java.io.BufferedReader br = new java.io.BufferedReader(new java.io.InputStreamReader(is));) {
            // 1. 获取输入流，接收数据


            while (true) {
                String msg = br.readLine();
                System.out.println("接收客户端的信息" + msg);
                //判断当前聊天形式
                if (msg.startsWith("all")) {
                    //群聊
                    sendMsgToall(msg);
                } else if (msg.startsWith("one")) {
                    //单聊
                } else {
                    //服务器聊天
                }
                if (Objects.equals(msg, "bye")) {
                    System.out.println(socket.getRemoteSocketAddress() + "客户强制推出");
                    break;
                }
            }
        } catch (Exception e) {
            System.out.println(socket.getRemoteSocketAddress() + "客户退出");
        }
    }

    private void sendMsgToall(String msg) throws IOException {
        //获取说有的客户端socket
        for (Socket value : Server.onlineUsers.values()) {
            OutputStream os=socket.getOutputStream();
            PrintWriter pw = new PrintWriter(os);
            pw.println( msg);
            pw.flush();
        }
            //遍历获取每一个socket的输出流


            //发送数据给每一个socket


    }
}
